<?php
	session_start();
	//make a response array to encode json...
	$response = array();
	// include db connect class
	require_once __DIR__ . '/db_connect.php';
	// connecting to db
	$db = new DB_CONNECT();
	if (isset($_GET['callback_redirect']) || isset($_GET['callback'])) {
		$cb = null;
		$current_question_order = 0;
		$email = "";
		if (isset($_GET['callback_redirect'])) {
			//redirect from game_starter.php, response as a question only, not check true/false
			$response["success"] = 1;
			$response["message"] = "the first question...";
			$cb = $_GET['callback_redirect'];
			$email = $_GET['email'];
		} else if (isset($_GET['callback'])) {
		//directly receive request from client, check true/false answer
			$response["success"] = 2;
			$response["message"] = "check true/false for current question and provide a new question";
			$cb = $_GET['callback'];
			//check true/false answer 
			$current_question_order = $_GET['current_question_order'];
			$answer = $_GET['answer'];
			$sql = "SELECT * FROM question_list WHERE auto_id=$current_question_order AND expected_answer='$answer'";
			$result = mysql_query($sql);
			$num_rows = mysql_num_rows($result);
			if ($num_rows == 1) { //true answer
				$sql = "UPDATE question_list SET status = 1 WHERE auto_id=$current_question_order";
				mysql_query($sql);
				
				$sql = "INSERT INTO temp_play_history VALUES ($current_question_order, '$email', 1)";
				mysql_query($sql);
				//save temp score to session corresponding to current user mail
				$email = $_GET['email'];
				$count = $_SESSION["$email"];
				$count++;
				$_SESSION["$email"] = $count;
			} else { //false answer
				//do nothing
				$sql = "INSERT INTO temp_play_history VALUES ($current_question_order, '$email', 0)";
				mysql_query($sql);
			}
		}
		

		//response as a question to client
		$sql = "SELECT * FROM question_list WHERE status = 0 AND auto_id > $current_question_order LIMIT 0, 1";
		$result = mysql_query($sql);
		$data_row = mysql_fetch_array($result);
		$num_rows = mysql_num_rows($result);
		if ($num_rows == 0) {
			//end game, make question_list empty and calculate score for every game player
			//$sql = 'TRUNCATE TABLE question_list';
			//mysql_query($sql);
			$response["success"] = 3;
			$response["message"] = "end game";
			date_default_timezone_set('Asia/Ho_Chi_Minh');
			$response["timestamp"] = date('l jS \of F Y h:i:s A');
		} else {
			$response["success"] = 2;
			$response["message"] = "check true/false for current question and provide a new question";
			//still have at least one question, continue to response a question to client
			$response["auto_id"] = $data_row[0];
			$response["question"] = $data_row[2];
			$response["answer_list"] = $data_row[3];
		}
		echo $cb."(".json_encode($response).");";
	}
?>